import * as THREE from 'three';
import {
    OrbitControls
} from 'three/addons/controls/OrbitControls.js';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';

export function init(container: HTMLElement) {
    const scene = new THREE.Scene();

    const axesHelper = new THREE.AxesHelper(2000);
    // scene.add(axesHelper);

    const width = container.clientWidth;
    const height = container.clientHeight;

    const camera = new THREE.PerspectiveCamera(60, width / height, 1, 1000);
    camera.position.set(200, 200, 200);
    camera.lookAt(0, 0, 0);

    const camera2 = new THREE.PerspectiveCamera(20, 16 / 9, 100, 300);
    let cameraHelper = new THREE.CameraHelper(camera2);
    scene.add(cameraHelper);

    const gui = new GUI();
    //  1. camera2.updateProjectionMatrix()
    // 更新相机的投影矩阵
    // 当相机的参数（如 fov、aspect、near、far）发生变化时，Three.js 不会自动重新计算投影矩阵
    // 必须手动调用这个方法来应用新的参数设置
    // 2. cameraHelper.update()
    // 更新相机助手的可视化显示
    // CameraHelper 是用来可视化相机视锥体的辅助对象
    // 当相机参数改变后，需要更新助手的显示来反映新的视锥体形状
    function onChange() {
        camera2.updateProjectionMatrix();
        cameraHelper.update();
    }
    gui.add(camera2, 'fov', [30, 60, 90]).onChange(onChange);
    gui.add(camera2, 'aspect', {
        '16/9': 16 / 9,
        '4/3': 4 / 3
    }).onChange(onChange);
    gui.add(camera2, 'near', 0, 300).onChange(onChange);
    gui.add(camera2, 'far', 300, 800).onChange(onChange);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height);

    let animationId: number;

    function render() {
        renderer.render(scene, camera);
        animationId = requestAnimationFrame(render);
    }

    render();

    container.appendChild(renderer.domElement);

    const controls = new OrbitControls(camera, renderer.domElement);

    // 窗口大小变化处理
    function handleResize() {
        const width = container.clientWidth;
        const height = container.clientHeight;
        camera.aspect = width / height;
        camera.updateProjectionMatrix();
        renderer.setSize(width, height);
    }

    window.addEventListener('resize', handleResize);

    // 返回清理函数
    return function cleanup() {
        window.removeEventListener('resize', handleResize);
        if (animationId) {
            cancelAnimationFrame(animationId);
        }
        controls.dispose();
        gui.destroy();
        renderer.dispose();
        if (container.contains(renderer.domElement)) {
            container.removeChild(renderer.domElement);
        }
    };
}
